<template>
  <div class="app-container bg">
    <!-- <div style="color: #fff;" @click="handleOpenImg">点击插图</div> -->
    <div style="margin-bottom: 10px;display: flex;justify-content: flex-end;" v-if="$route.query.id">
      <el-button type="primary" class="primary-btn" icon="el-icon-refresh-left" @click="$router.go(-1)">返回</el-button>
    </div>
    <div class="make-content">
      <!-- 左边区域 -->
      <div class="make-left" ref="makeLeftRef" :style="{ backgroundImage: `url(${backImageUrl})` }">
        <div class="make-btn" v-if="!imgSrc && !backImageUrl">
          <div style="display: flex;">
              <file-upload
                ref="imgUpload"
                :fileType="['jpg', 'png', 'webp']"
                :params="{ workDir }"
                :isShowTip="false"
                @input="uploadImg">
                <el-button type="primary" class="primary-btn">点击上传本地素材</el-button>
              </file-upload>

            <el-button style="margin-left: 20px;" type="primary"  @click="handleOpenImg">从系统中选择素材</el-button>
          </div>
        </div>

        <!-- 背景 -->
        <!-- <div style="position: absolute;left: 0;right: 0;top: 0;bottom: 0;z-index: 0;">
          <img :src="backImageUrl" style="width: 100%;" alt="">
        </div> -->
         <!-- 避免错位div -->
         <div style="display: none;">{{ isRect }}</div>
         <div
          class="target"
          id="target"
          :style="{ height: cutHeight+'px', width: cutWidth+'px' }"
          style="position:absolute;
          left: 0;
          top: 0;
          z-index: 1;">
          <img
          :src="imgSrc" alt=""
          v-if="imgSrc"
          >
          <canvas
            id="myCanvas"
            v-if="isMatting"
            :width="cutWidth"
            :height="cutHeight"
            ref="canvas"
            style="position: absolute;left: 0;right: 0;top: 0;bottom: 0;z-index: 2;"
            @mousedown="startDragging"
            @mousemove="dragging"
            @mouseup="stopDragging"
            @click="markPoint($event)"
            @contextmenu.prevent="handleRightClick"></canvas>
        </div>
        <div
          class="targets"
          v-if="isRect"
          style="width: 150px;height: 250px;position:absolute;left: 0;top: 0;z-index: 2;">
            <div style="height: 100%;">
            </div>
          </div>
          <!-- v-if="imgSrc" -->
        <Moveable
            v-if="imgSrc"
            className="moveable"
            v-bind:target="['.target']"
            v-bind:draggable="draggable"
            v-bind:resizable ="false"
            v-bind:scalable="scalable"
            v-bind:rotatable="false"
            v-bind:originDraggable ="true"
            v-bind:roundable ="false"
            v-bind:snappable="true"
            v-bind:keepRatio="true"
            @drag="onDrag"
            @scale="onScale"
            @rotate="onRotate"
        />
        <Moveable
            v-if="isRect"
            className="moveable"
            v-bind:target="['.targets']"
            v-bind:draggable="true"
            v-bind:resizable ="false"
            v-bind:scalable="true"
            v-bind:rotatable="false"
            v-bind:originDraggable ="false"
            v-bind:roundable ="false"
            @drag="onDragRect"
            @scale="onScaleRect"
            @rotate="onRotateRect"
        />
      </div>
      <!-- 右边区域 -->
      <div class="make-right">
        <div class="ai-write themm-black">
          <el-tabs v-model="activeName" @tab-click="changeTab">
            <!-- <el-tab-pane label="裁剪" name="tailor"></el-tab-pane>
            <el-tab-pane label="修复" name="repair"></el-tab-pane> -->
            <el-tab-pane label="抠图" name="matting"></el-tab-pane>
            <el-tab-pane label="滤镜" name="filter"></el-tab-pane>
            <!-- <el-tab-pane label="标注" name="label"></el-tab-pane> -->
            <el-tab-pane label="评估" name="evaluate"></el-tab-pane>
          </el-tabs>
          <!-- 裁剪 -->
          <div class="ai-write-form" v-if="activeName === 'tailor'">
            裁剪
          </div>
          <!-- 修复 -->
          <div class="material-content" v-if="activeName === 'repair'">
            修复
          </div>
          <!-- 抠图 -->
          <div class="material-content" v-if="activeName === 'matting'">
            <div class="">目标抠图</div>
            <div class="matting-item">
              <div class="btn" @click="handleMSelect(1)">点击选择</div>
              <div class="btn" @click="handleRect(2)">绘制矩形框</div>
              <div class="btn" @click="handleResetSelect()">重置</div>
            </div>
            <div class="matting-item">
              <div class="label">边缘宽度</div>
              <div class="slider"><el-slider v-model="borderWidh"></el-slider></div>
              <div class="num">{{ borderWidh }}px</div>
            </div>
            <div class="matting-item">
              <div class="btn">三原图预览</div>
              <div class="btn" @click="oneeCut">一键抠图</div>
            </div>
            <div class="label" style="margin-top: 20px;">背景修改</div>
            <div class="matting-item" style="align-items: center;">
              <div class="icon-img active" v-for="item in backgroundList" :key="item.id" @click="changeBackground(item)">
                <img :src="item.url" alt="">
                <!-- <div class="text">{{item.description}}</div> -->
              </div>
              <div class="" @click="changeBackground({name:'others.png'})">
                <el-button
                  style="width: 100%;margin-top: 0;padding: 8px 10px;"
                  type="primary"
                  class="primary-btn" size="mini">选择背景</el-button>
              </div>
            </div>
            <div class="matting-item">位置调整（鼠标拖动前景区域改变位置，滚轮调整大小，并可调整选择角度）</div>
            <div class="matting-item">前景背景和谐化</div>
            <div class="btn-box">
              <el-button
                style="width: 100%;"
                type="primary"
                class="primary-btn" size="medium" @click="handleOptimize">一键优化</el-button>
            </div>
          </div>
          <!-- 滤镜 -->
          <div class="material-content" v-if="activeName === 'filter'">
            <div class=""><img class="icon-img" src="~@/assets/icons/filter.png" alt="" />色彩</div>
            <div class="matting-item">
              <div class="label">亮度</div>
              <div class="slider">
                <el-slider :max='50' v-model="imageFilter.liangdu"></el-slider>
              </div>
              <div class="num">{{ imageFilter.liangdu }}</div>
            </div>
            <div class="matting-item">
              <div class="label">对比度</div>
              <div class="slider">
                <el-slider :max='50' v-model="imageFilter.duibidu"></el-slider>
              </div>
              <div class="num">{{ imageFilter.duibidu }}</div>
            </div>
            <!-- <div class="matting-item">
              <div class="label">饱和度</div>
              <div class="slider"><el-slider :max='50' v-model="borderWidh"></el-slider></div>
              <div class="num">{{ borderWidh }}</div>
            </div>
            <div class="matting-item">
              <div class="label">色温</div>
              <div class="slider"><el-slider :max='50' v-model="borderWidh"></el-slider></div>
              <div class="num">{{ borderWidh }}</div>
            </div> -->
            <div class="" style="margin-top: 20px;"><img class="icon-img" src="~@/assets/icons/filter.png" alt="" />滤镜</div>
            <div class="matting-item" style="margin-bottom: 40px;">
              <div class="icon-img" v-for="(item, index) in dict.type.image_filter" :key="index" @click="handleFilter(item.value)">
<!--                <img src="@/assets/icons/nature.png" alt="" :style="item.cssClass">-->
                <img
                  :src="imgSrc || backImageUrl || require('@/assets/icons/nature.png')"
                  alt=""
                  :style="getFilterStyles(item.raw.cssClass)"
                />
<!--                <div class="text">{{item.raw.cssClass}}</div>-->
                <div class="text">{{item.label}}</div>
              </div>
            </div>
            <div class="primary-btn" @click="addImageFilter">添加滤镜</div>
          </div>
          <!-- 评估 -->
          <div class="material-content" v-if="activeName === 'evaluate'">
            <div class="evaluate-con">
              <div class="evaluate-item">
                <span>真实度检测</span>
                <span>得分：{{taskImage.realityScore}}</span>
              </div>
              <div class="evaluate-item">
                <span>情绪值评估</span>
                <span>得分：{{ taskImage.emotionalScore }}</span>
              </div>
              <div class="evaluate-item">
                <span>引导力综合评估</span>
                <span>得分：{{ taskImage.totalScore }}</span>
              </div>
            </div>
            <div class="primary-btn" @click="oneeValuation">一键评估</div>
          </div>
          <div class="check-form">
            <!-- <el-checkbox-group v-model="checkList"> -->
              <el-checkbox v-model="savePrivate" label="保存到个人素材"></el-checkbox>
              <el-checkbox v-model="savePublic" label="保存到公共素材"></el-checkbox>
            <!-- </el-checkbox-group> -->
          </div>
        </div>


      </div>
    </div>
    <!-- 底部生成按钮 -->
    <div class="make-footer">
      <el-button type="primary" class="reset-btn" size="medium" @click="resetImg">重置</el-button>
      <el-button type="primary" class="green-btn" size="medium" @click="createImg">生成图片</el-button>
      <el-button type="primary" class="primary-btn" size="medium" @click="saveMaterial">保存素材</el-button>
    </div>
    <!-- 预览组件 -->
    <Preview ref="preview" />
    <img-material ref="imgMaterial" @insertion="insertion" />
    <!-- 确认生成图片 -->
    <el-dialog :visible.sync="dialogVisible" title="请确认是否生成图片"  width="500px" @close="cancel">
      <el-form label-position="top" ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="图片标题" prop="title">
              <el-input v-model="taskImage.title" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" class="primary-btn" @click="submitCreateImg">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 确认保存素材 -->
    <el-dialog :visible.sync="materialVisible" title="请确认是否保存素材"  width="500px" @close="cancel">
      <el-form label-position="top" ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="素材标题" prop="title">
              <el-input v-model="metaName" placeholder="请输入素材标题" maxlength="30" />
            </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" class="primary-btn" @click="submitSaveMaterial">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Moveable from 'vue-moveable';
// 功能组件
import  {fabric}  from 'fabric';
import { getInitTask,getFileTemplate,editImage,metaAdd,getTask,imageAssessment } from "@/api/content/task";
import { getImageInfo} from "@/api/material/material";
import { imageMatting,imageTrimapGeneration,backGroundReplace,addImageFilter } from "@/api/content/algorithm";//算法接口表
import Preview from "./components/Preview";
import ImgMaterial from "./components/ImgMaterial";


export default {
  name: "Task",
  dicts: ['image_filter'],
  components: { Preview, ImgMaterial,Moveable },
  data() {
    return {
      loading: true,
      activeName: 'matting',
      form: {},
      dialogVisible:false,
      materialVisible:false,
      borderWidh: 0,
      checkList: [],
      retrieveList: [],
      tabIndex: 'private',
      taskImage: {},
      workDir: '',
      rules: {},
      bgImg: {},
      savePrivate:false,
      savePublic:false,
      isSelBg: false,//是否选择了背景
      metaName: '',
      curMatting: null,//1点击选择，2绘制矩形，3重置
      pointLabel:[],//点坐标,1前景（左键），0背景（右键）
      isMatting: false,//是否已抠图
      imageFilter:{
        style:0,
        liangdu:0,
        duibidu:0
      },
      imgSrc: '',
      dPage:{},
      backgroundList:[],
      backImageUrl:'',//当前背景
      // 绘图
      markedPoints: [],//左键点坐标
      points: [],//右键点坐标
      isDragging: false, // 是否正在拖动
      dragStartPos: { x: 0, y: 0 }, // 拖动开始时的鼠标位置
      shape: { // 矩形的初始位置和尺寸
        x: 100,
        y: 100,
        width: 100,
        height: 300,
        strokeColor: 'black',
        strokeWidth: 2,
      },

      // 绘制描边矩形
      isResizing: false,
      resizingCorner: null,
      isDragging: false,
      dragStartPos: { x: 0, y: 0 },
      rectangle: {
        x: 100,
        y: 100,
        width: 200,
        height: 150,
      },
      corners: {
        topLeft: { x: 0, y: 0 },
        topRight: { x: 0, y: 0 },
        bottomLeft: { x: 0, y: 0 },
        bottomRight: { x: 0, y: 0 },
      },
      // 移动前置图片
      dragStartX: null,
      dragStartY: null,
      ctx: null,
      canvasMat:null,
      // 拖拽抠图
      draggable:false,
      scalable:false,//是否可以缩放
      // 背景图宽高
      bgWidth: 0,
      bgHeight: 0,
      bgSize:{},
      // 抠图宽高
      cutWidth: 0,
      cutHeight: 0,
      // 抠图位置
      cutLeft: 0,
      cutTop: 0,
      // 缩放比率
      cutScale: 1,
      // 定义矩形
      isRect:false,//是否显示矩形
      rectLeft: 0,
      rectTop: 0,
      corners:[]
    };
  },
  mounted() {
    if(this.$route.query.id){
      if(this.$route.query.type == 1){//1素材，2图片任务
        this.getInitTask()
      }else{
        this.getTask(this.$route.query.id)
      }
    }else{
      this.getInitTask()
    }
    this.getBackground()
  },
  methods: {
    getFilterStyles(cssClass) {
      if (typeof cssClass !== 'string') {
        console.error('getFilterStyles: cssClass is not a string', cssClass);
        return {}; // 返回一个空样式对象
      }

      const filters = cssClass.split(' ').map(filter => {
        if (!filter) return ''; // 如果 filter 是空字符串，跳过
        const [name, value] = filter.split('(');
        if (!name || !value) return ''; // 如果没有名称或值，跳过
        const functionName = name.trim();
        const args = value.slice(0, -1).trim(); // 移除闭合的括号并去除空格
        return `${functionName}(${args})`;
      }).filter(Boolean); // 移除空字符串

      return { filter: filters.join(' ') };
    },
    // 创建任务工作目录
    getInitTask() {
      getInitTask({ type: 'IMAGE' }).then(res => {
        console.log(res, '工作目录')
        this.taskImage = res.data.taskImage
        this.workDir = res.data.workDir
        if(this.$route.query.id){
          this.getImageInfo(this.$route.query.id)
        }
      })
    },
    // 获取图片任务详情
    getTask(id){
      getTask(id).then(res => {
        console.log(res,'ssss');
        this.taskImage = res.data.taskImage
        this.imgSrc = this.taskImage.finishedUrl
      })

    },
    // 获取图片素材详情
    getImageInfo(id) {
      getImageInfo(id).then(res => {
        console.log(res,'getImageInfo');
        res.imageUrl = res.data.preViewUrl
        this.imgSrc = res.data.preViewUrl
        this.taskImage.imageUrl = this.imgSrc
      })

    },
    // 获取背景图模板
    async getBackground() {
      const { data: res } = await getFileTemplate('background_image');
      console.log(res);
      this.backgroundList = res
    },
    // 获取滤镜
    async getBackground() {
      const { data: res } = await getFileTemplate('background_image');
      console.log(res);
      this.backgroundList = res
    },
    // 上传素材
    uploadImg(e){
      console.log(e)
      this.getImageSize(e).then(res => {
          this.cutWidth = res.width;
          this.cutHeight = res.height;
          // 当前div实际大小
          const rect = this.$refs.makeLeftRef.getBoundingClientRect();
          this.bgSize = {
            width: rect.width,
            height: rect.height
          };
          console.log('当前画布显示大小:', this.bgSize);
          // 计算图片宽高缩放

          this.imgSrc = e
          this.taskImage.imageUrl = e
          console.log(res)
        })
    },
    // 从本地选择素材插入
    insertion(item) {
      console.log(item.preViewUrl)
      if(this.isSelBg){
        this.$nextTick(() => {
          this.taskImage.backImageUrl = item.preViewUrl
          this.backImageUrl = item.preViewUrl
          this.getImageSize(item.preViewUrl).then(res => {
            // 背景图宽高
            this.bgWidth = res.width
            this.bgHeight = res.height
          })
          console.log(this.taskImage.backImageUrl,'myCanvasBg')
        })
      }else{
        // this.imgSrc = '@/assets/images/profile.jpg'
      // 通过图片src计算图片原始大小
        this.getImageSize(item.preViewUrl).then(res => {
          this.cutWidth = res.width;
          this.cutHeight = res.height;
          // 当前div实际大小
          const rect = this.$refs.makeLeftRef.getBoundingClientRect();
          this.bgSize = {
            width: rect.width,
            height: rect.height
          };
          console.log('当前画布显示大小:', this.bgSize);
          // 计算图片宽高缩放

          this.imgSrc = item.preViewUrl
          this.taskImage.imageUrl = item.preViewUrl
          console.log(res)
        })
      }

    },
    getImageSize(src) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => {
          resolve({
            width: img.naturalWidth,
            height: img.naturalHeight
          });
        };
        img.onerror = reject;
        img.src = src;
      });
    },

    // 绘制抠图背景
    drawCanvasBg(url) {
      console.log(url)
      this.taskImage.imageUrl = url
      // this.getInitTask()
      // 获取canvas元素
      this.canvasMat = this.$refs.canvasMat;
      console.log(this.canvasMat)
      this.ctx = this.canvasMat.getContext('2d');
      var ctx = this.canvasMat.getContext('2d');
      console.log(ctx,'111111111')

      // 创建新的Image对象
      var img = new Image();
      // 设置图片源为本地文件路径
      img.src = url;
      // 确保图片加载完成后再绘制到canvas
      let res = {}
      img.onload = function () {
        // 在canvas上绘制图片
        res = {
          width: img.width,
          height: img.height
        }
        // that.bgImg = res
        console.log(res); //获取到图片的宽高
        ctx.drawImage(img, 0, 0, res.width, res.height);
      };
    },
    handleOpenImg() {
      this.isSelBg = false
      this.$refs.imgMaterial.show(this.taskImage.taskId)
    },

    // 获取图片尺寸
    // getImageSize(event) {
    //   const img = event.target;
    //   this.imageWidth = img.naturalWidth;
    //   this.imageHeight = img.naturalHeight;
    // },
    // 切换tab
    changeTab() {

    },
    resetImg() {
      this.imgSrc = ''
      this.taskImage.imageUrl = ''
    },
    cancel(){
      this.dialogVisible = false
      this.materialVisible = false
    },
    // 生成图片任务
    createImg() {
      this.taskImage.title = this.parseTime(new Date())
      this.dialogVisible = true
    },
    async submitCreateImg(){
      console.log(this.taskImage)
      this.$modal.loading("正在生成，请稍候！");

      const {data } = await editImage(this.taskImage)
      console.log(data)
      this.cancel()
      this.$modal.closeLoading();
      this.$modal.msgSuccess('保存成功');
      // this.$router.push({
      //     path: '/content/task/list'
      //   })
    },
    // 保存素材
    async saveMaterial() {
      console.log(this.taskImage)
      if(!this.savePrivate && !this.savePublic){
       return this.$modal.msgError('请选择保存类型')
      }
      this.metaName = this.parseTime(new Date())
      this.materialVisible = true
    },
    async submitSaveMaterial(){
      const params = {
        id: this.taskImage.taskId,
        savePrivate:this.savePrivate,
        savePublic:this.savePublic,
        metaName:this.metaName
      }
      const { data } = await metaAdd(params)
      console.log(data)
      this.$modal.msgSuccess("保存成功");
      this.materialVisible = false

    },
    markPoint(event) {
      if (this.curMatting == 1) {
        const canvas = this.$refs.canvas;
        const ctx = canvas.getContext('2d');
        const rect = canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;

        // 标记点
        ctx.beginPath();
        ctx.arc(x, y, 5, 0, 2 * Math.PI);
        ctx.fillStyle = 'blue';
        ctx.fill();

        // 记录点的坐标
        this.points.push([x, y] );
        this.pointLabel.push(1);
        console.log(this.points,'this.markedPoints');
        console.log(this.pointLabel,'this.pointLabel');
      }

    },
    handleRightClick(event) {
      if (this.curMatting == 1) {
        event.preventDefault(); // 阻止默认右键菜单出现

        // 获取canvas的DOM元素和上下文
        const canvas = this.$refs.canvas;
        const ctx = canvas.getContext('2d');

        // 计算鼠标点击位置相对于canvas的位置
        const rect = canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;

        // 记录坐标
        this.points.push([x, y]);
        this.pointLabel.push(0);
        console.log(this.points,'this.markedPoints');
        console.log(this.pointLabel,'this.pointLabel');
        // 绘制标记点（可选）
        this.drawPoint(ctx, x, y);

        // 重新渲染列表，Vue会自动处理
      }
    },
    drawPoint(ctx, x, y) {
      ctx.beginPath();
      ctx.fillStyle = 'red'; // 标记点颜色
      ctx.arc(x, y, 5, 0, 2 * Math.PI); // 绘制圆形标记点
      ctx.fill();
    },
    // 绘制矩形
    drawShape() {
      this.isRect = true
      // const canvas = this.$refs.canvas;
      //   const ctx = canvas.getContext('2d');
      //   ctx.clearRect(0, 0, canvas.width, canvas.height);
      //   ctx.strokeStyle = this.shape.strokeColor;
      //   ctx.lineWidth = this.shape.strokeWidth;
      //   ctx.strokeRect(this.shape.x, this.shape.y, this.shape.width, this.shape.height);
    },
    startDragging(event) {
      if (this.isPointInsideShape(event.offsetX, event.offsetY)) {
        this.isDragging = true;
        this.dragStartPos = { x: event.offsetX, y: event.offsetY };
      }
    },
    dragging(event) {
      if (this.isDragging) {
        const dx = event.offsetX - this.dragStartPos.x;
        const dy = event.offsetY - this.dragStartPos.y;

        // 更新形状的位置
        this.shape.x += dx;
        this.shape.y += dy;

        // 重置拖动开始位置
        this.dragStartPos = { x: event.offsetX, y: event.offsetY };
        console.log(this.shape)
        // console.log(this.dragStartPos)
        console.log(this.getCanvasCorners(), '坐标位置')
      }
    },
    stopDragging() {
      this.isDragging = false;
    },
    isPointInsideShape(x, y) {
      return (
        x > this.shape.x &&
        x < this.shape.x + this.shape.width &&
        y > this.shape.y &&
        y < this.shape.y + this.shape.height
      );
    },
    // 获取矩形坐标
    getCanvasCorners() {
      const canvas = this.$refs.canvas; // 假设canvas元素绑定了ref="canvas"
      const rect = canvas.getBoundingClientRect(); // 获取canvas在视口中的布局信息

      // 计算四个角的坐标
      const topLeft = { x: rect.left, y: rect.top };
      const topRight = { x: rect.right, y: rect.top };
      const bottomLeft = { x: rect.left, y: rect.bottom };
      const bottomRight = { x: rect.right, y: rect.bottom };

      // 返回四个角的坐标
      return { topLeft, topRight, bottomLeft, bottomRight };
    },
    clearCanvas() {
      const canvas = this.$refs.canvas;
      const context = canvas.getContext('2d');

      // 使用clearRect清除整个canvas内容
      context.clearRect(0, 0, canvas.width, canvas.height);
    },
    // 抠图 区域
    // 点击选择
    handleMSelect(e) {

      this.curMatting = e
      this.isMatting = true;
      this.rectLeft = 0
      this.rectTop = 0
      this.isRect = false
    },
    // 选择矩形
    handleRect(e){
      this.curMatting = e
      // this.isMatting = true;
      this.points = []//清除点
        this.pointLabel = []//清除点
        this.drawShape();
        this.clearCanvas()//清除画布
    },
    // 重置选择
    handleResetSelect(){
      this.points = []
      this.pointLabel = []
      this.isMatting = false;
      this.isRect = false
    },
    // 目标抠图-图片分割
    async cut() {
      const { data } = await imageMatting({
        taskId: this.taskId,
        workDir: this.workDir,
        imageUrl: this.imageUrl,
        imageWidth: this.imageWidth,
        imageHeight: this.imageHeight,
        markedPoints: this.markedPoints,
      });
      console.log(data, '抠图预览')
    },
    // 一键抠图
    async oneeCut() {
      let splitConfig = {}
      if(this.curMatting===1){
        splitConfig = {
          point: this.points,
          point_label: this.pointLabel,
          // box:[this.rectLeft,this.rectTop]
        }
        delete splitConfig.box;
        console.log(splitConfig)
      }else{
        const toppos = [this.corners[0].x,this.corners[0].y]
        const bottompos = [this.corners[3].x,this.corners[3].y]
        splitConfig = {
          box:[...toppos,...bottompos]
        }
        delete splitConfig.point;
        delete splitConfig.point_label;
      }

      this.taskImage.splitConfig = splitConfig
      this.taskImage.trimapSize = this.borderWidh
      console.log(this.taskImage,'一键抠图入参')
      const { data } = await imageMatting(this.taskImage);
      console.log(data, '一键抠图预览')
      this.taskImage = data
      this.isMatting = false;
      this.isRect = false
      this.draggable = true//抠图后可拖拽
      this.scalable = true //抠图后可缩放
      // var canvas = document.getElementById('myCanvas');
      // const context = canvas.getContext('2d');
      // 使用clearRect清除整个canvas内容
      // context.clearRect(0, 0, canvas.width, canvas.height);
      // this.drawCanvasBg(data.finishedUrl)
      this.imgSrc = data.finishedUrl
      this.points = []//清除点
      this.pointLabel = []//清除点
      this.clearCanvas()//清除点
    },
    // 三原图生成后预览
    async createTripleArtwork(){
      const { data } = await imageTrimapGeneration({
        taskId: this.taskId,
        workDir: this.workDir,
        imageUrl: this.imageUrl,
        imageWidth: this.imageWidth,
        imageHeight: this.imageHeight,
        markedPoints: this.markedPoints,
      });
      console.log(data, '三原图生成后预览')
    },
    // 选择背景
    changeBackground(item){
      if(!this.imgSrc){
        return this.$message.error('请先选择素材')
      }
      console.log(item)
      // 如果是其他背景图弹出选择背景框
      if(item.name ==='others.png'){
        this.isSelBg = true
        this.$refs.imgMaterial.show()
      }else{
        this.$nextTick(() => {
          this.taskImage.backImageUrl = item.url
          this.backImageUrl = item.url
          this.getImageSize(item.url).then(res => {
            // 背景图宽高
            this.bgWidth = res.width
            this.bgHeight = res.height
          })
          console.log(this.taskImage.backImageUrl,'myCanvasBg')
        })
      }

    },
    getScaledElementPosition() {
      const element = document.getElementById('target');
      return element.getBoundingClientRect();
    },
    // 一键优化
    async handleOptimize(){
      // this.cutScale =this.bgSize.width / this.bgWidth
      const react =  this.getScaledElementPosition()
      console.log(react, 'react')
      const x = react.x - 30;
      const y = react.y - 30 - 92;
      console.log(this.cutScale, '------------------')
      this.taskImage.backImageUrl = this.backImageUrl
      this.taskImage.backGroundConfig = {
        sf: this.cutScale,
        pos_x: x,
        pos_y: y
      }
      console.log(this.taskImage,'一键优化入参');
      const {data} = await backGroundReplace(this.taskImage);
      console.log(data,'背景替换')
      this.backImageUrl = data.finishedUrl
      this.taskImage = data;
      this.imgSrc = ''
    },
    startDraggingMat(event) {
      this.dragStartX = event.clientX - this.canvasMat.offsetLeft;
      this.dragStartY = event.clientY - this.canvasMat.offsetTop;
      document.addEventListener('mousemove', this.dragging);
      document.addEventListener('mouseup', this.stopDragging);
    },
    draggingMat(event) {
      this.clearCanvasMat();
      const newX = event.clientX - this.dragStartX;
      const newY = event.clientY - this.dragStartY;
      this.drawCanvasBg(this.taskImage);
    },
    stopDraggingMat() {
      document.removeEventListener('mousemove', this.dragging);
      document.removeEventListener('mouseup', this.stopDragging);
    },
    clearCanvasMat() {
      this.ctx.clearRect(0, 0, this.canvasMat.width, this.canvasMat.height);
    },
    // 抠图区域结束
    // 滤镜区域
    handleFilter(value){
      this.imageFilter.style  = value
      // this.addImageFilter()
    },
    // 添加滤镜
    async addImageFilter(){
      this.taskImage.imageFilter = this.imageFilter
      this.$modal.loading("正在生成，请稍候！");
      const {data} = await addImageFilter(this.taskImage);
      this.$modal.closeLoading();
      console.log(data,'添加滤镜')
      // this.drawCanvasBg(data.finishedUrl)
      // this.imgSrc = data.finishedUrl
      this.backImageUrl = data.finishedUrl
      this.taskImage = data;
      this.imgSrc = ''
    },
    // 一键评估
    async oneeValuation() {
      this.$modal.loading("正在评估中，请稍候！");
      const { data } = await imageAssessment(this.taskImage);
      console.log(data, '一键评估后预览')
      this.$modal.msgSuccess('评估成功');
      this.$modal.closeLoading();
      this.taskImage = data
    },
    // 移动抠图
    onDrag(e) {
      console.log(e)
      const clientX = e.translate[0]
      const clientY = e.translate[1]
      // console.log(target, transform)
      this.cutLeft = clientX
      this.cutTop = clientY

      console.log(clientX, clientY)
      // console.log(result, '333333333333333333333333333')
      e.target.style.transform = e.transform;
    },

    onScale({ target, drag }) {
      console.log(target, drag, '----------------')
      var values = drag.transform.split('(')[2].split(')')[0].split(',');
      var a = values[0];
      // 对于2D转换，a和d是等价的，所以我们只需要检查a
      var scale = (a * 1).toFixed(2);
      this.cutScale = scale;
      console.log(values, '-999999999999999999999999999999')
      target.style.transform = drag.transform;
    },

    onRotate({ target, drag }) {
      console.log(target, drag)
      target.style.transform = drag.transform;
    },
    // 移动矩形
    onDragRect(e){
      console.log(e)
      e.target.style.transform = e.transform;
      const { beforeTranslate,transform} = e
      const extractScale = this.extractScale(transform)
      let widths = e.width
      let heights = e.height
      const left = beforeTranslate[0];
      const top = beforeTranslate[1];
      if(extractScale?.length > 1){
        widths = e.width * extractScale[0]
        heights = e.height * extractScale[1]
      }
      const right = left + widths;
      const bottom = top + widths;
      const corners = [
        { x: left, y: top },
        { x: right, y: top },
        { x: left, y: bottom },
        { x: right, y: bottom }
      ];
      this.corners = corners;
      console.log('四个角的坐标:' , corners )

    },
    onScaleRect({ target, drag }) {
      // console.log(target, drag)
      target.style.transform = drag.transform;
      const { beforeTranslate,width, height } = drag
      const extractScale = this.extractScale(drag.transform)
      let widths = width
      let heights = height
      const left = beforeTranslate[0];
      const top = beforeTranslate[1];
      if(extractScale.length > 1){
        widths = width * extractScale[0]
        heights = height * extractScale[1]
      }
      const right = left + widths;
      const bottom = top + widths;
      const corners = [
        { x: left, y: top },
        { x: right, y: top },
        { x: left, y: bottom },
        { x: right, y: bottom }
      ];
      this.corners = corners;
      console.log('四个角的坐标:' , corners )
    },
    onRotateRect({ target, drag }) {
      console.log(target, drag)
      target.style.transform = drag.transform;
      const { beforeTranslate,left, top, width, height } = drag

      console.log(this.extractScale(drag.transform),'transform')
      const right = left + width;
      const bottom = top + height;
      const corners = [
        { x: left, y: top },
        { x: right, y: top },
        { x: left, y: bottom },
        { x: right, y: bottom }
      ];
    },
    // 解析缩放倍数
    extractScale(transformStr) {
      const scaleMatch = transformStr.match(/scale\(([^)]+)\)/);
      if (scaleMatch) {
        const scaleArgs = scaleMatch[1].split(',').map(arg => parseFloat(arg.trim()));
        return scaleArgs;
      }
      return null;
    }
  },
};
</script>
<style lang="scss" scoped>
.body {
  overflow: hidden !important;
}

.bg {
  background-image: url("../../../assets/images/content_bg.png");
  background-size: 25%;
  background-repeat: no-repeat;
  background-position: top right;
}

.make-content {
  display: flex;
  .icon-img{
    width: 15px;
    height: 15px;
    vertical-align: middle;
    margin-right: 2px;
  }

}
.make-left {
  height: 643px;
  position: relative;
  flex: 1;
  margin-right: 20px;
  background: rgba(255, 255, 255, .1);
  padding: 20px;
  border-radius: 12px;
  overflow: hidden;
  background-size: auto; /* 使背景图适应容器 */
  // background-position: center; /* 图片居中 */
  background-repeat: no-repeat;
  // canvas{
  //   width: 100%;
  //   height: 100%;
  // }
}

.make-right {
  width: 564px;
  color: #fff;

  .matting-item {
    display: flex;
    align-items: center;
    margin-top: 20px;

    .label {
      width: 60px;
    }

    .btn {
      background: rgba(255, 255, 255, 0.1);
      border-radius: 4px;
      padding: 6px 16px;
      margin-right: 10px;
      cursor: pointer;
    }

    .slider {
      width: 300px;
      margin: 0 20px;
    }

    .num {
      background: rgba(255, 255, 255, 0.1);
      padding: 4px 12px;
      font-size: 12px;
      border-radius: 4px;
    }
    .active{
      border: 2px solid #fff;
    }
    .icon-img {
      text-align: center;
      margin-right: 20px;
      width: 60px;
      height: 60px;
      box-sizing: border-box;
      img {
        width: 100%;
        height: 100%;
        cursor: pointer;
      }

      .text {
        font-size: 12px;
        color: rgba(255, 255, 255, .6);
      }
    }
  }

  .evaluate-con {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    padding: 5px 15px;

    .evaluate-item {
      display: flex;
      justify-content: space-between;
      padding: 10px 0
    }
  }

  .primary-btn {
    text-align: center;
    padding: 10px 0;
    border-radius: 4px;
    margin-top: 20px;
    cursor: pointer;
  }
}

.check-form {
  margin-top: 20px;
}

.ai-write {
  height: 543px;
  background: rgba(255, 255, 255, .1);
  border-radius: 12px;
  padding: 10px 20px 20px;

  .ai-write-btn {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;

    .el-button {
      flex: 1;
      padding: 13px 0;
      font-size: 16px;
    }
  }

  .create-content {
    margin-top: 10px;
  }

  .form-btn {
    margin-top: 20px;

    .el-button {
      padding: 13px 0;
      font-size: 16px;
      width: 100%;
    }
  }
}

.make-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  background: rgba(255, 255, 255, .1);
  border-radius: 12px;
  padding: 20px;

  .el-button {
    margin-left: 20px;
  }
}

.tab-list {
  margin: 20px 0;
  align-items: center;

  .right-btn {
    flex: 1;
    text-align: right;
    color: rgba(255, 255, 255, .6);

    .btn-item {
      margin-left: 40px;
      cursor: pointer;
    }

    .btn-item.active {
      color: rgba(0, 87, 255, 1);
      border-bottom: 1px solid rgba(0, 87, 255, 1);
      padding-bottom: 10px;
    }
  }
}

.make-btn {
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 10;
  text-align: center;
  transform: translate(-50%,-50%);
  img{
    width: 100px;
    height: 100px;
    margin-bottom: 30px;
  }
}

// 网格背景
.design-stage-grid {
  --offsetX: 0px;
  --offsetY: 0px;
  --size: 16px;
  --color: #dedcdc;
  background-image: linear-gradient(
      45deg,
      var(--color) 25%,
      transparent 0,
      transparent 75%,
      var(--color) 0
    ),
    linear-gradient(45deg, var(--color) 25%, transparent 0, transparent 75%, var(--color) 0);
  background-position: var(--offsetX) var(--offsetY),
    calc(var(--size) + var(--offsetX)) calc(var(--size) + var(--offsetY));
  background-size: calc(var(--size) * 2) calc(var(--size) * 2);
}







::v-deep .ql-toolbar.ql-snow {
  border: none;
  background: #F7F8FA;
}

::v-deep .ql-container.ql-snow {
  border: none;
}

::v-deep .make-right .el-tabs__item {
  color: #fff;
}

::v-deep .el-tabs__nav-wrap::after {
  height: 1px;
  background: #4D4E5F;
}

::v-deep .el-tabs__item:hover {
  color: #0057FF;
}

::v-deep .el-tabs__item.is-active {
  color: #0057FF;
}

::v-deep .el-tabs__active-bar {
  background: #0057FF;
}

::v-deep {
  .el-slider__bar {
    height: 4px;
    background: rgba(255, 255, 255, 1);
  }

  .el-slider__runway {
    background: rgba(255, 255, 255, .4);
    height: 4px;
    margin: 0;
  }

  .el-slider__button {
    width: 3px;
    height: 6px;
    border: none;
    margin-bottom: 3px;
    border-radius: 0;
  }
  .el-dialog__headerbtn .el-dialog__close{
    color: #000;
    font-size: 20px;
  }
  .el-form--label-top .el-form-item__label{
    padding-bottom: 0;
    font-weight: normal;
  }

  .rCS1w3zcxh .moveable-control{
    width: 5px;
    height: 5px;
    margin-top: -3px;
    margin-left: -3px;
    border: none;
  }
}
</style>
